<template>
  <div class="shoppingCart" :class="isShow ? 'empty' : ''">
    <header>
      购物车({{ total_count }})
      <span class="action" @click="changeStatus">{{
        status === 1 ? "管理" : "完成"
      }}</span>
    </header>
    <div class="content-wrapper">
      <md-check-group v-model="insurants" style="height: 100%">
        <md-scroll-view
          ref="scrollView"
          :scrolling-x="false"
          :auto-reflow="true"
          @endReached="onEndReached"
          @refreshing="onRefresh"
        >
          <md-scroll-view-refresh
            slot="refresh"
            slot-scope="{ scrollTop, isRefreshActive, isRefreshing }"
            :scroll-top="scrollTop"
            :is-refreshing="isRefreshing"
            :is-refresh-active="isRefreshActive"
          ></md-scroll-view-refresh>
          <md-result-page
            v-show="isShow"
            style="margin-top: 30px"
            text="购物车竟然是空的"
            subtext="在忙也要记得买的什么犒劳自己~"
          ></md-result-page>
          <div class="cart" v-for="(info, index) in data" :key="index">
            <div class="check-box">
              <md-check :name="info" />
            </div>
            <div
              class="img-box"
              @click.stop.self="
                $commonJs.goPage('goodsDetail', info.product_id)
              "
            >
              <img :src="$api.imgUrl + JSON.parse(info.img)[0]" alt="" />
            </div>
            <div
              class="content"
              @click.stop.self="
                $commonJs.goPage('goodsDetail', info.product_id)
              "
            >
              <span class="name">{{ info.name }}</span>
              <div class="count-box">
                <span class="money">￥{{ info.price }}</span>
                <md-stepper
                  slot="right"
                  v-model="info.num"
                  read-only
                  min="1"
                  @change="changeNum(info.num, info.product_id)"
                ></md-stepper>
              </div>
            </div>
          </div>
          <md-scroll-view-more
            slot="more"
            :is-finished="isFinished"
            finished-text="已经到底啦~"
          >
          </md-scroll-view-more>
        </md-scroll-view>
      </md-check-group>
    </div>
    <footer>
      <md-check v-model="checkedAll" label="全选"></md-check>
      <div>
        <span class="total" v-if="status === 1"
          >合计:
          <span class="money"
            >￥<md-amount :value="totalMoney" has-separator></md-amount>元
          </span></span
        >
        <md-button
          @click="changeInfo"
          type="default"
          round
          inline
          :plain="status === 1 ? false : true"
          >{{ status === 1 ? "结算" : "删除" }}</md-button
        >
      </div>
    </footer>
  </div>
</template>

<script>
import {
  ResultPage,
  ScrollView,
  ScrollViewMore,
  ScrollViewRefresh,
  Button,
  Check,
  Stepper,
  CheckGroup,
  Amount
} from "mand-mobile";
import { debounce } from "@/tool/public";

export default {
  name: "index",
  components: {
    [ResultPage.name]: ResultPage,
    [ScrollView.name]: ScrollView,
    [ScrollViewMore.name]: ScrollViewMore,
    [ScrollViewRefresh.name]: ScrollViewRefresh,
    [Amount.name]: Amount,
    [Stepper.name]: Stepper,
    [Check.name]: Check,
    [CheckGroup.name]: CheckGroup,
    [Button.name]: Button
  },
  data() {
    return {
      isShow: false,
      status: 1, // 1是管理,2 是删除
      checkedAll: false,
      insurants: [],
      curpage: 1,
      data: [],
      total_count: 0,
      total_page: 1,
      isFinished: false,
      preList: {} //产品id和数量
    };
  },
  methods: {
    changeNum: debounce(function(num, id) {
      if (this.preList[id] !== num) {
        this.$ajax
          .post(
            this.$api.shopCarAction,
            {
              product_id: id,
              num: num
            },
            false
          )
          .then(() => {
            this.preList[id] = num;
          })
          .catch(err => {
            this.$toast.failed(err);
          });
      }
    }, 800),
    changeStatus() {
      if (this.status === 1) {
        this.status = 2;
      } else {
        this.status = 1;
      }
    },
    changeInfo() {
      if (this.status === 1) {
        this.settlement();
      } else {
        this.delGoods();
      }
    },
    settlement() {
      if (this.insurants.length > 0) {
        let arr = [];
        this.insurants.forEach(item => {
          let obj = JSON.parse(item);
          arr.push(obj.id);
        });
        this.$ajax
          .post(
            this.$api.saveShopCar,
            {
              shop_id: JSON.stringify(arr)
            },
            false
          )
          .then(() => {
            this.$commonJs.goPage("shoppingCartOrder");
          })
          .catch(err => {
            this.$toast.failed(err);
          });
      } else {
        this.$toast.failed("请选择结算商品");
      }
    },
    delGoods() {
      if (this.insurants.length > 0) {
        let arr = [];
        this.insurants.forEach(item => {
          let obj = JSON.parse(item);
          arr.push(obj.id);
        });
        this.$ajax
          .post(
            this.$api.deleteShopCar,
            {
              shop_id: JSON.stringify(arr)
            },
            false
          )
          .then(() => {
            this.insurants = [];
            this.getInfo(true);
          })
          .catch(err => {
            this.$toast.failed(err);
          });
      } else {
        this.$toast.failed("请选择您想要删除的商品");
      }
    },
    onEndReached() {
      if (this.isFinished) {
        return;
      }
      this.curpage++;
      this.getInfo();
    },
    onRefresh() {
      this.$nextTick(() => {
        this.curpage = 1;
        this.isFinished = false;
        this.getInfo(true);
      });
    },
    getInfo(refresh) {
      this.$ajax
        .post(
          this.$api.shopCarList,
          {
            curpage: this.curpage
          },
          false
        )
        .then(res => {
          if (refresh) {
            this.data = res.data.data;
            this.$refs.scrollView.finishRefresh();
          } else {
            this.data.push.apply(this.data, res.data.data);
          }
          if (this.curpage === res.data.total_page) {
            this.isFinished = true;
          }
          this.$refs.scrollView.finishLoadMore();
          if (this.checkedAll) {
            this.insurants = [];
            this.data.forEach(item => {
              this.insurants.push(item);
            });
          }
          if (this.data.length === 0) {
            this.isShow = true;
          }
          this.changePreList();
          this.total_count = res.data.total_count;
          this.total_page = res.data.total_page;
        })
        .catch(err => {
          this.$toast.failed(err);
        });
    },
    changePreList() {
      this.preList = {};
      this.data.forEach(item => {
        this.preList[item.product_id] = item.num;
      });
    }
  },
  mounted() {
    this.$refs.scrollView.triggerRefresh();
  },
  computed: {
    totalMoney() {
      if (this.insurants.length > 0 && this.preList) {
        let total = 0;
        this.insurants.forEach(item => {
          total += item.num * item.price;
        });
        return total;
      } else {
        return 0;
      }
    }
  },
  watch: {
    insurants(val) {
      if (val.length === this.data.length) {
        this.checkedAll = true;
      } else {
        this.checkedAll = false;
      }
    },
    checkedAll(val) {
      if (!val) {
        if (this.insurants.length === this.data.length) {
          this.insurants = [];
        }
      } else {
        if (this.insurants.length < this.data.length) {
          this.insurants = [];
          this.data.forEach(item => {
            this.insurants.push(item);
          });
        }
      }
    }
  }
};
</script>

<style scoped lang="stylus">
  .total{
    display inline-block
    margin-right 20px
    font-size:24px;
    font-family:PingFang-SC-Medium;
    font-weight:500;
    .money{
      color:#ED721B;
    }
  }
.shoppingCart{
    flex_content();
    flex_column();
    height: 100%;
    font-size 0
  }
    .content-wrapper{
      flex: auto;
      height 100%
      padding 33px 24px
      overflow hidden
}
header{
  height: 88px;
  text-align center;
  line-height 88px;
  background white;
  border-bottom 1px solid #D6D6D6
  font-size:36px;
  font-family:PingFang-SC-Regular;
  color:rgba(51,51,51,1);
  position relative
  .action{
    position absolute;
    right  24px;
    line-height 88px;
    font-size:24px;
  }
}
  footer{
    height 98px;
    padding 0 24px
    background white;
    flex_content();
    flex_align_center();
    flex_justify_space();
  }
  .cart{
    background white
    border-radius 15px
    padding 30px 20px
    flex_content()
    margin-bottom 10px
    .check-box{
      align-self: center
      margin-right 28px
    }
    .img-box{
      margin-right 24px
    }
    img{
      height 176px
      width 176px
    }
    .content{
      flex_one()
      display inline-block;
      padding 22px 0
      font-size 24px
      flex_content();
      flex_column();
      flex_justify_space()
      .name{
        color #666666
      }
      .money{
        color #ED721B
      }
    }
    .count-box{
      flex_content()
      flex_align_center()
      flex_justify_space()
    }
  }
</style>
